const { spawn } = require('child_process');
const chokidar = require('chokidar')
const { resolve } = require('path')
const env = {
    GIT_PATH: '/Users/mac/Documents/web/bootstrap/git/tmp',
    RESOURCE_AVATAR: '/Users/mac/Documents/web/bootstrap/git/resource/avatar',
    GIT_HTTP_PATH: 'http://127.0.0.1:7005/api',
    DB_PATH: '/Users/mac/Documents/web/bootstrap/git/db',
    PORT: '7005',
    SECRET_KEY: "qwwdasdsadasdasdasdasdaasd",
}
Object.assign(process.env, env)
function runtime(src, log) {
    let child = null
    let timer = null
    function run() {
        if (timer !== null) {
            return;
        }
        timer = setTimeout(() => {
            clearTimeout(timer)
            timer = null;
        }, 30)
        if (child) {
            child.kill()
        }
        child = spawn('node', [resolve(src)], {
            env: process.env,
        })
        child.stdout.on('data', function (buffer) {
            console.log(`-------------------${log} success -------------------`);
            console.log(buffer.toString('utf-8'))
        })
        child.stderr.on('data', err => {
            console.log(`-------------------${log} fail -------------------`);
            console.log(err.toString('utf-8'))
        })
    }
    run()
    return run
}

// backend
const backendRuntime = runtime('src/index.js', 'backend')

const backendWatcher = chokidar.watch(resolve('src'), {
    // ignored: /assets/, // ignore dotfiles
    ignoreInitial: true,
    persistent: true
});
backendWatcher.on('all', function (event) {
    console.clear()
    console.log('update', event)
    backendRuntime()
})